#!/usr/bin/env node

/**
 * 图片优化示例和测试脚本
 * 演示如何使用高级图片优化器
 */

const AdvancedImageOptimizer = require('../lib/utils/advanced-image-optimizer');
const ImageOptimizationConfig = require('../lib/config/image-optimization-config');
const path = require('path');

async function demonstrateImageOptimization() {
    console.log('🖼️  高级图片优化演示\n');

    // 初始化优化器
    const optimizer = new AdvancedImageOptimizer();
    const configManager = new ImageOptimizationConfig();

    // 测试图片路径（请替换为实际存在的图片路径）
    const testImages = [
        // 请提供一些测试图片路径，例如：
        // './test-images/large-screenshot.png',
        // './test-images/design-mockup.jpg',
        // './test-icons/small-icon.png'
    ];

    // 如果没有测试图片，创建一个模拟的base64图片
    if (testImages.length === 0) {
        console.log('📝 没有找到测试图片，使用模拟数据演示...\n');
        await demonstrateWithMockData(optimizer, configManager);
        return;
    }

    // 处理实际图片
    for (const imagePath of testImages) {
        try {
            await processImage(optimizer, configManager, imagePath);
        } catch (error) {
            console.error(`❌ 处理图片失败 ${imagePath}:`, error.message);
        }
        console.log('---\n');
    }
}

async function demonstrateWithMockData(optimizer, configManager) {
    // 创建一个模拟的PNG图片（1x1像素）
    const mockPNG = createMockPNG();
    console.log(`📊 模拟图片信息: ${mockPNG.length} bytes`);

    // 演示不同任务类型的优化
    const taskTypes = [
        'generate_html_from_prototype',
        'analyze_design_screenshot',
        'compare_image',
        'extract_component_hierarchy',
        'default'
    ];

    for (const taskType of taskTypes) {
        console.log(`\n🎯 任务类型: ${taskType}`);

        // 获取任务配置
        const config = configManager.getAutoConfig(
            { sizeMB: mockPNG.length / 1024 / 1024, format: 'png' },
            taskType
        );

        console.log(`   配置: ${configManager.getConfigSummary(config)}`);
        console.log(`   说明: ${config.qualityDescription || config.description || '无说明'}`);

        // 执行优化
        try {
            const result = await optimizer.optimizeImage(mockPNG, config);

            if (result.optimizedInfo.optimized) {
                console.log(`   ✅ 优化成功:`);
                console.log(`      原始: ${result.originalInfo.size} bytes (${result.originalInfo.format})`);
                console.log(`      优化后: ${result.optimizedInfo.size} bytes (${result.optimizedInfo.format})`);
                console.log(`      压缩率: ${((1 - result.optimizedInfo.size / result.originalInfo.size) * 100).toFixed(1)}%`);
            } else {
                console.log(`   ℹ️  无需优化`);
            }
        } catch (error) {
            console.log(`   ❌ 优化失败: ${error.message}`);
        }
    }
}

async function processImage(optimizer, configManager, imagePath) {
    console.log(`📁 处理图片: ${path.basename(imagePath)}`);

    try {
        // 分析原始图片
        const originalInfo = await optimizer.parseImage(imagePath);
        console.log(`   原始信息:`);
        console.log(`     大小: ${originalInfo.sizeMB}MB`);
        console.log(`     格式: ${originalInfo.format}`);
        console.log(`     尺寸: ${originalInfo.width}x${originalInfo.height}`);

        // 演示不同质量等级的优化效果
        const qualityLevels = ['high', 'medium', 'low', 'ultra'];

        for (const quality of qualityLevels) {
            console.log(`\n   🔧 质量等级: ${quality}`);

            const config = configManager.getQualityConfig(quality);
            const startTime = Date.now();

            const result = await optimizer.optimizeImage(imagePath, config);
            const processingTime = Date.now() - startTime;

            if (result.optimizedInfo.optimized) {
                console.log(`     ✅ 优化成功 (${processingTime}ms):`);
                console.log(`       大小: ${result.originalInfo.sizeMB}MB -> ${result.optimizedInfo.sizeMB}MB`);
                console.log(`       压缩率: ${((1 - result.optimizedInfo.size / result.originalInfo.size) * 100).toFixed(1)}%`);
                console.log(`       格式: ${result.originalInfo.format} -> ${result.optimizedInfo.format}`);
                console.log(`       尺寸: ${result.originalInfo.width}x${result.originalInfo.height} -> ${result.optimizedInfo.width}x${result.optimizedInfo.height}`);
            } else {
                console.log(`     ℹ️  无需优化 (${processingTime}ms)`);
            }
        }

    } catch (error) {
        console.error(`   ❌ 处理失败: ${error.message}`);
    }
}

function createMockPNG() {
    // 创建一个最小的1x1像素PNG图片
    return Buffer.from([
        0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, // PNG签名
        0x00, 0x00, 0x00, 0x0D, // IHDR长度
        0x49, 0x48, 0x44, 0x52, // IHDR
        0x00, 0x00, 0x00, 0x01, // 宽度: 1
        0x00, 0x00, 0x00, 0x01, // 高度: 1
        0x08, 0x02, 0x00, 0x00, 0x00, // 位深度和颜色类型
        0x90, 0x77, 0x53, 0xDE, // CRC
        0x00, 0x00, 0x00, 0x0C, // IDAT长度
        0x49, 0x44, 0x41, 0x54, // IDAT
        0x08, 0x99, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00,
        0x00, 0x02, 0x00, 0x01, // IEND长度
        0x49, 0x45, 0x4E, 0x44, // IEND
        0xAE, 0x42, 0x60, 0x82  // CRC
    ]);
}

async function testPerformance() {
    console.log('\n⚡ 性能测试\n');

    const optimizer = new AdvancedImageOptimizer();
    const mockPNG = createMockPNG();
    const iterations = 100;

    console.log(`测试迭代次数: ${iterations}`);
    console.log(`模拟图片大小: ${mockPNG.length} bytes`);

    const startTime = Date.now();

    for (let i = 0; i < iterations; i++) {
        const config = {
            maxFileSize: 1024, // 1KB
            targetQuality: 0.7,
            enableLossyCompression: true,
            stripMetadata: true
        };

        await optimizer.optimizeImage(mockPNG, config);
    }

    const totalTime = Date.now() - startTime;
    const avgTime = totalTime / iterations;

    console.log(`总时间: ${totalTime}ms`);
    console.log(`平均时间: ${avgTime.toFixed(2)}ms`);
    console.log(`处理速度: ${(1000 / avgTime).toFixed(0)} 图片/秒`);
}

async function showConfigurationOptions() {
    console.log('\n⚙️  配置选项示例\n');

    const configManager = new ImageOptimizationConfig();

    // 显示不同任务的配置
    const tasks = [
        'generate_html_from_prototype',
        'analyze_design_screenshot',
        'compare_image',
        'extract_component_hierarchy'
    ];

    for (const task of tasks) {
        const config = configManager.getTaskConfig(task);
        console.log(`📋 ${task}:`);
        console.log(`   ${configManager.getConfigSummary(config)}`);
        console.log(`   说明: ${config.description || '无说明'}`);
        console.log('');
    }

    // 显示质量等级配置
    console.log('🎚️ 质量等级配置:');
    const qualityLevels = configManager.defaultConfig.qualityLevels;
    for (const [level, config] of Object.entries(qualityLevels)) {
        console.log(`   ${level}: 质量=${config.quality}, 最大尺寸=${config.maxDimension}px`);
        console.log(`        ${config.description}`);
    }
}

// 主函数
async function main() {
    console.log('🖼️  Vision Analyzer - 图片优化演示\n');

    if (process.argv.includes('--performance')) {
        await testPerformance();
    } else if (process.argv.includes('--config')) {
        await showConfigurationOptions();
    } else {
        await demonstrateImageOptimization();
    }

    console.log('\n✅ 演示完成！');
}

// 运行演示
if (require.main === module) {
    main().catch(console.error);
}

module.exports = {
    demonstrateImageOptimization,
    testPerformance,
    showConfigurationOptions
};